package org.iabako.server.servlet;

import org.apache.log4j.Logger;
import org.iabako.server.serviceimpl.security.SessionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by jose on 15/12/14.
 */
public class PaymentCancelServlet extends HttpServlet {

    static Logger log = Logger.getLogger(PaymentCancelServlet.class.getName());

    private final String PATH_TO_PROPERTIES = "/WEB-INF/classes/org/iabako/conf/iabako.properties";
    private final String URL_PAYMENT_CANCEL_PROPERTY = "url_payment_cancel";

    @Autowired
    SessionUser sessionUser;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        log.info("Payment have been cancelled...");

        //It comes back from PayPal
        if (sessionUser != null && sessionUser.getUser() != null) {
            sessionUser.getUser().setGoToPayPal(false);
        }

        Properties prop = new Properties();
        prop.load(getServletContext().getResourceAsStream(PATH_TO_PROPERTIES));

        response.sendRedirect(prop.getProperty(URL_PAYMENT_CANCEL_PROPERTY));
    }
}
